﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace com.lib.manager
{
   public class TimerManager
    {
       private static TimerManager instance = null;


       private int id = 0;

      

       public delegate void TimerManagerCallBack(TimerManagerData dt);


       private Dictionary<int, Thread> mdata = new Dictionary<int, Thread>();


       private List<TimerManagerData> nd = new List<TimerManagerData>();


       public static TimerManager Instance
       {
           get
           {
               if (instance == null)
               {
                   instance = new TimerManager();
               }
               return instance;
           }
       }


       public int AddTimer(float del,int count,TimerManagerCallBack call, object dt )
       {
           int tempdat = getId();
           Hashtable hash = new Hashtable();
           hash["del"] = del;
           hash["count"] = count;
           hash["id"] = tempdat;
           hash["call"] = call;
           hash["dt"] = dt;
           var pr = new ParameterizedThreadStart(AddTimerThread);
           var thread = new Thread(pr);
           thread.Start(hash);
           mdata.Add(tempdat, thread);
           return tempdat;
       }

       public void Update()
       {
           if (nd.Count > 0)
           {
               nd[0].call(nd[0]);
               nd.RemoveAt(0);
           }

       }

       public void StopTimer(int id)
       {
           if (mdata.ContainsKey(id))
           {
               mdata[id].Abort();
               mdata.Remove(id);
           }

       }

       private void AddTimerThread(object o)
       {
           Hashtable hash = o as Hashtable;
           float del = Convert.ToSingle(hash["del"]);
           int count = hash["count"].getInt();
           int mid = hash["id"].getInt();
           var dt =hash["dt"];
           TimerManagerCallBack call = (TimerManagerCallBack)hash["call"];
           count = count == 0 ? 200000000 : count;
           int fream = 1;
           for (int i = 0; i < count; i++)
           {
               Thread.Sleep((int)(del * 1000));
               TimerManagerData rm = new TimerManagerData();
               rm.fream = fream;
               rm.id = mid;
               rm.data = dt;
               rm.call = call;
               nd.Add(rm);
               fream += 1;
           }
       }

       private int getId()
       {
           lock (mdata)
           {
               id = id + 1;
               return id;
           }

       }

    }
}

public class TimerManagerData
{
    public int fream { get; set; }

    public object data { get; set; }

    public int id { get; set; }

    public com.lib.manager.TimerManager.TimerManagerCallBack call { get; set; }

}